package com.woniuxy.authentication;

import com.woniuxy.exception.NoPermissionException;
import com.woniuxy.utils.LoginUser;
import com.woniuxy.utils.UserUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
import java.util.List;

/**
 * 鉴权切面类
 */
@Aspect
@Component
public class PersAspect {

    @Autowired
    private UserUtils userUtils;

    /**
     * 给标注了PermissionAuth注解的方法切入
     */
    @Pointcut(value = "@annotation(com.woniuxy.authentication.PermissionAuth)")
    public void myPointcut() {
    }

    /**
     * 环绕通知
     * @param proceedingJoinPoint
     * @return
     * @throws Throwable
     */
    @Around("myPointcut()")
    public Object persAuth(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        MethodSignature methodSignature = (MethodSignature) proceedingJoinPoint.getSignature();
        Method method = methodSignature.getMethod();
        checkPermissions(method);
        return proceedingJoinPoint.proceed();
    }

    /**
     * 检查权限
     * @param method
     */
    private void checkPermissions(Method method) {
        PermissionAuth annotation = method.getAnnotation(PermissionAuth.class);
        if (annotation != null) {
            String annotationValue = annotation.value();
            //得到该用户的LoginUser对象
            LoginUser loginUser = userUtils.getLoginUser();
            //得到该用户的所有权限
            List<String> perms = loginUser.getUserAllPers();
            if (!perms.contains(annotationValue)) {//没有权限
                throw new NoPermissionException();
            }
        }
    }
}
